package com.wtwd.device.service.impl;


import com.wtwd.device.constant.RespCode;
import com.wtwd.device.dao.AppDeviceMapper;
import com.wtwd.device.model.entity.Device;
import com.wtwd.device.model.entity.UpgradeFile;
import com.wtwd.device.model.entity.UpgradeVo;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author mjy
 * @date 2021/08/11
 * @description
 */
@Service
public class AppDeviceServiceImpl implements AppDeviceService {

    @Autowired
    private AppDeviceMapper appDeviceMapper;

    @Autowired
    private AppUpgradeService appUpgradeService;

    @Autowired
    private StepService stepService;

    @Autowired
    private HeartRateService heartRateService;

    @Autowired
    private SleepRecordService sleepRecordService;

    @Autowired
    private BloodPressureRecordService bloodPressureRecordService;

    @Autowired
    private BloodOxygenRecordService bloodOxygenRecordService;

    @Autowired
    private BloodSugarRecordService bloodSugarRecordService;

    @Autowired
    private AppSportRecordService appSportRecordService;

    @Autowired
    private TempRecordService tempRecordService;

    @Value("${upgrade.file}")
    private String upgradeFile;
    @Value("${file.http}")
    private String fileHttp;
    @Value("${file.path}")
    private String filePath;


    @Override
    public RespEntity userBindDevice(Long userId, String macAddress, String name, String uuId) {
        Device watch = appDeviceMapper.getDeviceByMacAddress(macAddress);
        if (watch != null) {
            //根据用户id,查询该用户是否已经绑定设备(如已经绑定请解绑设备后重新绑定设备)
            Device device = appDeviceMapper.getDeviceByAppUserId(userId);
            if (device != null &&  !watch.getId().equals(device.getId())) {
                return new RespEntity(RespCode.ALREADY_BIND_DEVICE_IS_APP_USER);
            }
            watch.setAppUserId(userId);
            //此处更新手表的最后上传时间，是为了处理，获取用户设备列表时的排序
            watch.setUpdateTime(new Date().getTime());
            watch.setName(name);
            watch.setUuId(uuId);
            Integer rest = appDeviceMapper.updateDeviceInfo(watch);
            return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAIL);

        }
        return new RespEntity(RespCode.WEB_NOP_RECORD);
    }

    @Override
    public RespEntity getUserDeviceList(Integer currentPage, Integer pageSize, Long userId) {
        Integer start = pageSize * currentPage;
        List<Device> watches = appDeviceMapper.getUserDeviceList(start, pageSize, userId);
        return new RespEntity(RespCode.SUCCESS, watches);
    }

    @Override
    public RespEntity unbindDevice(Long userId, String macAddress) {
        Device device = appDeviceMapper.getDeviceByMacAddress(macAddress);
        if (device.getAppUserId() == null) {
            return new RespEntity(RespCode.DEVICE_NOT_BOUND);
        }
        Integer rest = appDeviceMapper.unbindDevice(userId, macAddress);
        return new RespEntity(RespCode.SUCCESS);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespEntity unbindDeviceAndClearUserInfo(Long userId, String macAddress) {
        Integer rest = appDeviceMapper.unbindDevice(userId, macAddress);
        //清除运动健康数据(运动健康还为开发,暂不处理)
        if (rest > 0) {//清除用户运动数据
            Device device = appDeviceMapper.getDeviceByMacAddress(macAddress);
            if (device == null) {
                return new RespEntity(RespCode.WEB_NOP_RECORD);
            }
            //清除步数
            stepService.deleteStepByDeviceId(device.getId());
            //清除心率
            heartRateService.deleteHeartRateByDeviceId(device.getId());
            //清除睡眠数据
            sleepRecordService.deleteSleepRecordByDeviceId(device.getId());
            //清除血压数据
            bloodPressureRecordService.deletePressureRecordByDeviceId(device.getId());
            //清除血氧数据
            bloodOxygenRecordService.deleteBloodOxygenRecordByDeviceId(device.getId());
            //清除血糖数据
            bloodSugarRecordService.deleteBloodSugarRecordByDeviceId(device.getId());
            //清除体温数据
            tempRecordService.deleteTempRecordByDeviceId(device.getId());
            //清除运动数据
            appSportRecordService.deleteSportRecordByDeviceId(device.getId());
        }
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAIL);
    }

    @Override
    public RespEntity<Device> getWatchByMacAddress(String macAddress) {
        Device watch = appDeviceMapper.getDeviceByMacAddress(macAddress);
        return new RespEntity(RespCode.SUCCESS, watch);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespEntity<UpgradeVo> checkForUpdate(String watchId, String currentFirmware, String language, String macAddress) {
        Device device = appDeviceMapper.getDeviceByMacAddress(macAddress);
        if (device == null) {//保证手表入库
            new RespEntity<>(RespCode.WEB_NOP_RECORD);
        }
        if (StringUtils.isBlank(device.getCurrentFirmware())) {//首次连接
            appDeviceMapper.updateDeviceCurrentFirmware(macAddress, currentFirmware);
        } else {
            if (!device.getCurrentFirmware().equals(currentFirmware)) {//发生变化(同时同步上次版本)
                appDeviceMapper.updateDeviceCurrentFirmwareAndPreviousVersion(macAddress, currentFirmware, device.getCurrentFirmware());
                //(因为app那边不能检测到固件是否升级成功，所以为配合，检测到该版本发生变化,就认为固件更新成功,更新人数加一)
                UpgradeFile upgradeFile = appUpgradeService.getUpGradeByWatchIdAndVersion(watchId, currentFirmware);
                if (upgradeFile != null) {//通过其他途径升级了，不统计
                    upgradeFile.setUpgradeNum(upgradeFile.getUpgradeNum() + 1);
                    appUpgradeService.updateUpgradeFile(upgradeFile);
                }
            }
        }
        //按文档直接对比大小
        List<UpgradeVo> upgradeVos = appUpgradeService.getDeviceUpgradeListByWatchId(watchId, language);
        UpgradeVo upgradeVo = new UpgradeVo();
        if (upgradeVos != null && upgradeVos.size() > 0) {
            upgradeVo = upgradeVos.stream().max(Comparator.comparing(UpgradeVo::getSubVersion)).get();
            if (upgradeVo.getSubVersion().compareTo(currentFirmware) > 0) {//有最新版本需要更新
                upgradeVo.setUpdateFlag(1);
            } else {//无最新版本
                upgradeVo.setUpdateFlag(0);
            }
            String filePath = upgradeVo.getFilePath();
            upgradeVo.setFilePath(fileHttp.concat(upgradeFile).concat(filePath));
        } else {//无升级包
            upgradeVo.setUpdateFlag(0);
        }
        return new RespEntity(RespCode.SUCCESS, upgradeVo);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespEntity updateDevice(Integer id, String targetFirmware, String macAddress) {
        Device watch = appDeviceMapper.getDeviceByMacAddress(macAddress);
        if (watch != null) {
            watch.setPreviousVersion(watch.getCurrentFirmware());
            watch.setCurrentFirmware(targetFirmware);
            //更新设备当前版本
            appDeviceMapper.updateDeviceInfo(watch);
            //更新该升级包中的升级人数
            UpgradeFile upgradeFile = appUpgradeService.getUpgradeById(id);
            upgradeFile.setUpgradeNum(upgradeFile.getUpgradeNum() + 1);
            appUpgradeService.updateUpgradeFile(upgradeFile);
            return new RespEntity(RespCode.SUCCESS);
        }
        return new RespEntity(RespCode.WEB_NOP_RECORD);
    }

    @Override
    public RespEntity activeDevice(String macAddress, String watchId, Long activeTime, Integer activation, String lng, String lat, String area) {
        Device device = appDeviceMapper.getDeviceByMacAddress(macAddress);
        Integer rest = 0;
        if (device == null) {
            return new RespEntity(RespCode.WEB_NOP_RECORD);
        }
        //鉴别设备是否已经激活
        if (device.getActivation() == null || device.getActivation().equals(0)) {//激活设备并同步激活时间(为激活状态)
            rest = appDeviceMapper.activeDevice(macAddress, watchId, activeTime, activation, lng, lat, area);
        } else {//已经激活(直接给success，方便app处理)
            return new RespEntity(RespCode.SUCCESS);
        }
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAIL);
    }

    /**
     * 清除一般的运动数据:
     * 计步,睡眠
     *
     * @param date
     * @return
     */
    @Override
    public boolean clearSportDataByDate(String date) {
        return appDeviceMapper.clearSportDataByDate(date);
    }

    @Override
    public Device getDeviceByUserId(long userId) {
        return appDeviceMapper.getDeviceByAppUserId(userId);
    }

    @Override
    public Long getDeviceIdByImei(String imei) {
        Device device = getDeviceInfoByImei(imei);
        if (device != null) {
            return device.getId();
        }
        return null;
    }

    @Override
    public Device getDeviceInfoByImei(String imei) {
        if (StringUtils.isEmpty(imei)) {
            return null;
        }
        return appDeviceMapper.getDeviceByImei(imei);
    }


    /**
     * @param str
     * @param flag
     * @return
     */
    public static String subString(String str, String flag) {
        String substring1 = str.substring(str.indexOf(flag) + 1);//去掉第一个元素
        String substring2 = substring1.substring(substring1.indexOf(flag) + 1);//去掉第二个元素;
        return substring2;
    }


}



